package com.yupi.springbootinit.bizmq;

import cn.hutool.core.util.StrUtil;
import com.rabbitmq.client.Channel;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.manager.AiManager;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.service.ChartService;
import com.yupi.springbootinit.utils.ExcelUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static com.yupi.springbootinit.bizmq.BiMqConstant.BI_QUEUE_NAME;
import static com.yupi.springbootinit.constant.CommonConstant.BI_MODEL_ID;

/**
 * @version 1.0
 * @Author moresuo
 * @Date 2024/3/6 22:56
 * @注释 消息消费者
 */
@Component
@Slf4j
public class BiMessageConsumer {
    @Resource
    private ChartService chartService;
    @Resource
    private AiManager aiManager;


    @SneakyThrows
    @RabbitListener(queues = {BI_QUEUE_NAME},ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag){
        log.info("receiveMessage:{}", message);
        if(StrUtil.isBlank(message)){
            //拒绝当前消息，让消息重新进入消息队列
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "消息为空");
        }
        long chartId = Long.parseLong(message);
        Chart chart = chartService.getById(chartId);
        if(chart==null){
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图表为空");
        }
        //先将任务状态设置为执行中，等执行成功后修改为已完成，执行失败修改为失败状态
        Chart updateChart=new Chart();
        updateChart.setId(chart.getId());
        updateChart.setStatus("running");
        boolean b = chartService.updateById(updateChart);
        if(!b){
            //执行失败
            handleChartUpdateError(chart.getId(), "更新图表执行状态失败");
            return;
        }

        //调用ai拿到返回结果
        String resultData = aiManager.doChat(BI_MODEL_ID,buildUserInput(chart));
        //对结果进行拆分
        String[] splits = resultData.split("【【【【【");
        //拆分之后的数据应该为3份
        if(splits.length<3){
            handleChartUpdateError(chart.getId(), "AI生成错误");
            return;
        }
        String genChart = splits[1].trim();//图表数据
        String genResult = splits[2].trim();//图表分析结论
        //调用ai成功后再次更新数据库
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chart.getId());
        updateChartResult.setGenChart(genChart);
        updateChartResult.setGenResult(genResult);
        updateChartResult.setStatus("succeed");
        boolean updateResult = chartService.updateById(updateChartResult);
        if(!updateResult){
            channel.basicNack(deliveryTag,false,false);
            handleChartUpdateError(chart.getId(), "更新图表成功状态失败");
        }
        channel.basicAck(deliveryTag,false);//消息确认
    }
    private String buildUserInput(Chart chart){
        //用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");
        //拼接分析目标
        String userGoal=chart.getGoal();
        String chartType= chart.getChartType();
        String chartData = chart.getCharData();
        if(StringUtils.isNotBlank(chartType)){
            userGoal += ",请使用" + chartType;
        }
        userInput.append(userGoal).append("\n");
        userInput.append("原始数据：").append("\n");
        //压缩后的数据
        userInput.append(chartData).append("\n");
        return userInput.toString();
    }
    private void handleChartUpdateError(long chartId,String execMessage){
        Chart chart = new Chart();
        chart.setId(chartId);
        chart.setStatus("failed");
        chart.setExecMessage(execMessage);
        boolean flag = chartService.updateById(chart);
        if(!flag){
            log.error("更新图表状态失败"+chartId+","+execMessage);
        }
    }
}
